import md5 from 'crypto-js/md5';
import {
    codeToText
} from "element-china-area-data";
import {
    getConfig,
    getUserId,
    getToken
} from "./auth";
import XLSX from 'xlsx/dist/xlsx.full.min.js';
import FileSaver from 'file-saver';

//加密平台标识
const OS = 'web';
//加密盐
const SALT = 'emhhHaC';

//获取请求头
export const getHeader = () => {
    const timeStamp = Date.now() + '';
    const sign = '01' + md5(timeStamp + SALT);
    let obj = {
        'os': OS,
        'x-time': timeStamp,
        'x-sign': sign,
    };
    if (getToken()) {
        obj['token'] = getToken();
    }
    if (getUserId()) {
        obj['userId'] = getUserId();
    }
    return obj;
}

//把区域码转成汉字
export const getCodeToText = (codeArray) => {
    let area = [];
    switch (codeArray.length) {
        case 1:
            area.push(codeToText[codeArray[0]])
            break;
        case 2:
            area.push(codeToText[codeArray[0]])
            area.push(codeToText[codeArray[1]])
            break;
        case 3:
            area.push(codeToText[codeArray[0]])
            area.push(codeToText[codeArray[1]])
            area.push(codeToText[codeArray[2]])
            break;
        default:
            break;
    }
    return area;
}


//上传图片地址
export const uploadUrl = 'https://api.zhgylgl.com/api/uploadImg';

//德信账户
export const dexinBankNumber = '4105250101500084019999';

//获取公共数据列表
export const publicList = () => {
    let globalInfo = getConfig();
    if (!globalInfo) return {};
    let carLong, carType, goodsType, unit; //目前用到四个公共数据 车长 车型 货物类型 货物单位

    carType = globalInfo.carType;
    unit = globalInfo.unit;
    goodsType = globalInfo.goodsType.map(item => ({
        name: item,
        key: item
    }));
    carLong = globalInfo.carLong.map(item => ({
        name: item,
        key: item
    }));

    return {
        carLong,
        carType,
        goodsType,
        unit,
        validityPeriodTime: globalInfo.validityPeriodTime
    };
}


//深克隆方法
export const deepClone = (obj) => {
    let objClone = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === "object") {
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                //判断ojb子元素是否为对象，如果是，递归复制
                if (obj[key] && typeof obj[key] === "object") {
                    objClone[key] = deepClone(obj[key]);
                } else {
                    //如果不是，简单复制
                    objClone[key] = obj[key];
                }
            }
        }
    }
    return objClone;
}

//返回一个秒为单位的时间戳 ,转换为2024/01/01 08:00:00
export function transformDate(time) {
    const timestamp = time;
    const date = new Date(timestamp * 1000);
    return date.toLocaleString();
}


//下载后端返回的文件
export const downloadFile = (url) => {
    var oReq = new XMLHttpRequest();
    //处理发票明细下载接口
    if (url.indexOf('https') == -1) {
        url = url.replace('http://', 'https://');
    }
    // The Endpoint of your server
    let fileName = (url + '').replace('http://img.zhgylgl.com/', '').replace('https://img.zhgylgl.com/', '');
    var URLToPDF = url;
    // Configure XMLHttpRequest
    oReq.open("GET", URLToPDF, true);
    // Important to use the blob response type
    oReq.responseType = "blob";
    // When the file request finishes
    // Is up to you, the configuration for error events etc.
    oReq.onload = function () {
        // Once the file is downloaded, open a new window with the PDF
        // Remember to allow the POP-UPS in your browser
        var file = new Blob([oReq.response], {
            type: "application/pdf"
        });
        // Generate file download directly in the browser !
        // saveAs(file, "mypdffilename.pdf");
        saveAs(file, decodeURIComponent(fileName));
    };
    oReq.send();
}

//与上次记录的时间戳对比
export const diffLastTimeStamp = () => {
    let time = 60; //分钟为单位
    let lastTimestamp = sessionStorage.getItem("lastTimestamp");
    sessionStorage.setItem("lastTimestamp", Date.now());
    if (lastTimestamp && !isNaN(lastTimestamp)) {
        lastTimestamp = Number(lastTimestamp);
        let current = Date.now();
        if (current - lastTimestamp > (time * 60 * 1000)) {
            return true;
        }
    }
}
//复制一段文本到剪切板
export const copyText = (text) => {
    // var text = document.getElementById('textToCopy').value;
    var input = document.createElement('input');
    input.setAttribute('value', text);
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
}

//获取当前月的天数
export function getDaysInCurrentMonth() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;

    switch (month) {
        case 2:
            if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
                return 29;
            } else {
                return 28;
            }
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            default:
                return 31;
    }
}

//get参数&化
export function convertObjectToQueryString(obj) {
    let queryString = '';
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (false) {
                if (obj[key]) {
                    queryString += key + '=' + obj[key].join('/') + '&';
                }
            } else {
                queryString += key + '=' + obj[key] + '&';

            }
        }
    }
    return queryString.slice(0, -1);
};

export function timestampToTime(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
}

//获取一个月前的时间戳
export function getOneMonthAgoTimestamp() {
    const now = new Date(); // 当前时间
    now.setMonth(now.getMonth() - 1); // 设置为一个月前的时间
    return now.getTime(); // 获取时间戳
};

//抹零方法
export const handleMoney = (num) => {
    num = Number(num);
    if (isNaN(num)) return 0; //用户输入的不是数字返回0
    //首先取整
    num = parseInt(num);
    //向下取整抹零
    let restNum = num % 10
    num = num - restNum;
    //返回数字带两位小数
    return {
        number: num.toFixed(2),
        restNum: restNum
    }

}

//姓名和手机号中间四位替换为*
export const maskString = (input = '') => {
    if (!input) return '';

    // 判断是否为手机号
    if (/^1[3-9]\d{9}$/.test(input)) {
        // 手机号中间四位替换为*
        return input.slice(0, 3) + '****' + input.slice(7);
    }
    //特殊处理汉字名称后面带数字情况
    let lastNum = input.slice(-1);
    if(input.length < 6 && !isNaN(lastNum)){
        let preNam = input.slice(0, -1);
        //此时再判断前面得是否为汉字
        if(/^[\u4e00-\u9fa5]+$/.test(preNam)){
            const length = preNam.length;
            if (length === 2) {
                // 二字姓名，第二位替换为*
                return preNam[0] + '*' + lastNum;
            } else if (length === 3) {
                // 三字姓名，第二位替换为*
                return preNam[0] + '*' + preNam[2] + lastNum;
            } else if (length === 4) {
                // 四字姓名，中间两位替换为*
                return preNam[0] + '**' + preNam[3] + lastNum;
            }
        }
    }


    // 判断是否为汉字姓名
    if (/^[\u4e00-\u9fa5]+$/.test(input)) {
        const length = input.length;
        if (length === 2) {
            // 二字姓名，第二位替换为*
            return input[0] + '*';
        } else if (length === 3) {
            // 三字姓名，第二位替换为*
            return input[0] + '*' + input[2];
        } else if (length === 4) {
            // 四字姓名，中间两位替换为*
            return input[0] + '**' + input[3];
        }
    }

    // 银行卡号 子账号中间四位替换为*
    return input.slice(0, 5) + '********' + input.slice(13);

    // 如果不是手机号或汉字姓名，返回原字符串
    return input;
}


//导出数据到excel表
export function exportDataToExcel(worksheetData, name = '导出数据', sheetDes = '') {
    const ws = XLSX.utils.json_to_sheet(worksheetData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, sheetDes);

    // 导出文件
    const excelBuffer = XLSX.write(wb, {
        bookType: 'xlsx',
        type: 'array'
    });
    const blob = new Blob([excelBuffer], {
        type: 'application/octet-stream'
    });

    FileSaver.saveAs(blob, name + '.xlsx');
}